package cn.kimming.rpc.demo.lb.service.impl;

import cn.kimming.rpc.common.annotation.RpcService;
import cn.kimming.rpc.common.constant.RpcConstant;
import cn.kimming.rpc.demo.lb.service.LoadBalanceService;
import cn.kimming.rpc.remoting.registry.InstanceDetail;
import cn.kimming.rpc.remoting.registry.ServerRpcRegistry;
import org.apache.curator.x.discovery.ServiceInstance;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;

@RpcService(value = LoadBalanceService.class, version = "1.0.0", description = "负载均衡服务, 返回本机服务地址和端口, 用于演示负载均衡效果")
public class LoadBalanceServiceImpl implements LoadBalanceService, EnvironmentAware {

    private Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public String testLoadBalance() {
        String address = null;
        Integer port = environment.getProperty(RpcConstant.MY_RPC_SERVER_PORT, Integer.class);
        try {
            address = InetAddress.getLocalHost().getHostAddress();
            Collection<ServiceInstance<InstanceDetail>> serviceInstances = ServerRpcRegistry.getDiscovery().queryForInstances(LoadBalanceService.class.getCanonicalName());
            for (ServiceInstance<InstanceDetail> serviceInstance : serviceInstances) {
                if (serviceInstance.isEnabled() &&
                        serviceInstance.getAddress().equals(address) &&
                        serviceInstance.getPort().equals(port)) {
                    return serviceInstance.getId();
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
